package speakershareserver;

import java.io.DataInputStream;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.*;

public class Server implements Runnable{

    ServerSocket serverSocket;
    Socket clientSocket;
    SourceDataLine sourceDataLine;
    DataInputStream in;
    byte[] chunk;

    public void run() {
        try {
            sourceDataLine = AudioSystem.getSourceDataLine(Settings.audioFormat);
            sourceDataLine.open(Settings.audioFormat);
            sourceDataLine.start();

            serverSocket = new ServerSocket(Settings.PORT);
            System.out.println("Listening...");
            clientSocket = serverSocket.accept();
            System.out.println("Accepted.");
            in = new DataInputStream(clientSocket.getInputStream());

            chunk = new byte[Settings.CHUNK_SIZE];

            while (true) {
                in.readFully(chunk);
                System.out.println("Read.");
                sourceDataLine.write(chunk, 0, chunk.length);
            }
        } catch (Exception ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String args[]){
        Thread t = new Thread(new Server());
        t.start();
    }
}
